<template>
  <div class="content-page">
    <div class="page-header">
      <h1>Content Management</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        Add Content
      </el-button>
    </div>
    
    <el-card>
      <div class="table-toolbar">
        <el-input
          v-model="searchText"
          placeholder="Search content..."
          style="width: 300px"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="statusFilter" placeholder="Filter by status" style="width: 150px">
          <el-option label="All" value="" />
          <el-option label="Published" value="published" />
          <el-option label="Draft" value="draft" />
        </el-select>
      </div>
      
      <el-table v-loading="loading" :data="filteredContent" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="Title" />
        <el-table-column prop="authorName" label="Author" width="120" />
        <el-table-column prop="contentType" label="Type" width="100" />
        <el-table-column label="Status" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isPublished ? 'success' : 'info'">
              {{ row.isPublished ? 'Published' : 'Draft' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Created" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editContent(row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button
              v-if="!row.isPublished"
              size="small"
              type="success"
              @click="publishContent(row)"
            >
              Publish
            </el-button>
            <el-button
              v-else
              size="small"
              type="warning"
              @click="unpublishContent(row)"
            >
              Unpublish
            </el-button>
            <el-button size="small" type="danger" @click="deleteContent(row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- Create/Edit Content Dialog -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingContent ? 'Edit Content' : 'Create Content'"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="contentFormRef"
        :model="contentForm"
        :rules="contentRules"
        label-width="120px"
      >
        <el-form-item label="Title" prop="title">
          <el-input v-model="contentForm.title" />
        </el-form-item>
        
        <el-form-item label="Content Type">
          <el-select v-model="contentForm.contentType" style="width: 200px">
            <el-option label="HTML" value="html" />
            <el-option label="Markdown" value="markdown" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="Content" prop="body">
          <div class="editor-container">
            <QuillEditor
              v-model:content="contentForm.body"
              content-type="html"
              :options="editorOptions"
              style="height: 400px"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="Status">
          <el-switch
            v-model="contentForm.isPublished"
            active-text="Published"
            inactive-text="Draft"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="cancelEdit">Cancel</el-button>
        <el-button type="primary" :loading="saving" @click="saveContent">
          {{ editingContent ? 'Update' : 'Create' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import api from '@/api'

interface Content {
  id: number
  title: string
  body: string
  contentType: string
  authorId: number
  authorName: string
  isPublished: boolean
  createdAt: string
  updatedAt?: string
  publishedAt?: string
}

const content = ref<Content[]>([])
const loading = ref(false)
const saving = ref(false)
const searchText = ref('')
const statusFilter = ref('')
const showCreateDialog = ref(false)
const editingContent = ref<Content | null>(null)
const contentFormRef = ref<FormInstance>()

const contentForm = reactive({
  title: '',
  body: '',
  contentType: 'html',
  isPublished: false
})

const contentRules: FormRules = {
  title: [
    { required: true, message: 'Please input content title', trigger: 'blur' }
  ],
  body: [
    { required: true, message: 'Please input content body', trigger: 'blur' }
  ]
}

const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image', 'video']
    ]
  }
}

const filteredContent = computed(() => {
  let filtered = content.value

  if (searchText.value) {
    filtered = filtered.filter(item =>
      item.title.toLowerCase().includes(searchText.value.toLowerCase()) ||
      item.authorName.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }

  if (statusFilter.value) {
    if (statusFilter.value === 'published') {
      filtered = filtered.filter(item => item.isPublished)
    } else if (statusFilter.value === 'draft') {
      filtered = filtered.filter(item => !item.isPublished)
    }
  }

  return filtered
})

const loadContent = async () => {
  loading.value = true
  try {
    const response = await api.get('/contents')
    content.value = response.data
  } catch (error) {
    ElMessage.error('Failed to load content')
  } finally {
    loading.value = false
  }
}

const editContent = (item: Content) => {
  editingContent.value = item
  contentForm.title = item.title
  contentForm.body = item.body
  contentForm.contentType = item.contentType
  contentForm.isPublished = item.isPublished
  showCreateDialog.value = true
}

const deleteContent = async (item: Content) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to delete content "${item.title}"?`,
      'Confirm Delete',
      {
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    
    await api.delete(`/contents/${item.id}`)
    ElMessage.success('Content deleted successfully')
    loadContent()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete content')
    }
  }
}

const publishContent = async (item: Content) => {
  try {
    await api.post(`/contents/${item.id}/publish`)
    ElMessage.success('Content published successfully')
    loadContent()
  } catch (error) {
    ElMessage.error('Failed to publish content')
  }
}

const unpublishContent = async (item: Content) => {
  try {
    await api.post(`/contents/${item.id}/unpublish`)
    ElMessage.success('Content unpublished successfully')
    loadContent()
  } catch (error) {
    ElMessage.error('Failed to unpublish content')
  }
}

const saveContent = async () => {
  if (!contentFormRef.value) return
  
  await contentFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (editingContent.value) {
          await api.put(`/contents/${editingContent.value.id}`, contentForm)
          ElMessage.success('Content updated successfully')
        } else {
          await api.post('/contents', contentForm)
          ElMessage.success('Content created successfully')
        }
        
        showCreateDialog.value = false
        loadContent()
        resetForm()
      } catch (error) {
        ElMessage.error(editingContent.value ? 'Failed to update content' : 'Failed to create content')
      } finally {
        saving.value = false
      }
    }
  })
}

const cancelEdit = () => {
  showCreateDialog.value = false
  resetForm()
}

const resetForm = () => {
  editingContent.value = null
  Object.assign(contentForm, {
    title: '',
    body: '',
    contentType: 'html',
    isPublished: false
  })
  contentFormRef.value?.resetFields()
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

onMounted(() => {
  loadContent()
})
</script>

<style scoped>
.content-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.table-toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
  align-items: center;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.ql-editor) {
  min-height: 300px;
}

:deep(.ql-toolbar) {
  border-bottom: 1px solid #dcdfe6;
}
</style>
